//
//  DCIMConversationViewController.m
//  xmppBase
//
//  Created by striby on 16/1/7.
//  Copyright © 2016年 com.dc. All rights reserved.
//

#import "DCIMConversationViewController.h"
#import "DTImageScale.h"
#import "UIImage+UIImage_FixOrientation.h"
#import "DCIMMapViewController.h"

static int tempCount = 30;

@interface DCIMConversationViewController ()
{
    DCChatInputView * inputView;
    
    NSMutableArray *dataSource ;
    
    NSMutableArray * tempTextCellArray;
    
    NSMutableArray * tempImageCellArray;
    
    CGPoint willBeginDeceleratePoint;
}

@property(nonatomic,strong)XMPPRoom * room;
@end

@implementation DCIMConversationViewController

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    if (_contactObj) {
        _contactObj.unReadCount=0;
        
        [[XMPPMessageArchivingCoreDataStorage sharedInstance].mainThreadManagedObjectContext save:nil];
        
        [_contactObj didUpdateObject];
    }
    
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    if (_contactObj) {
        _contactObj.unReadCount=0;
        
        [[XMPPMessageArchivingCoreDataStorage sharedInstance].mainThreadManagedObjectContext save:nil];
        
        [_contactObj didUpdateObject];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    
    if (self.conversationType==DCConversationTypeGroup) {
        DCIMGroupManager * groupManager = [DCIMGroupManager shareInstance];
        
        self.room =  [groupManager joinRoomWithRoomJid:self.targetJID];
        NSString * roomName = [[DCIMGroupManager shareInstance]getRoomNameWithRoomJid:self.room.roomJID];;
       
        if (roomName) {
            self.title = roomName;
        }
        else
        {
            [self.room fetchConfigurationForm];
        }
        
    }
    else if (self.conversationType==DCConversationTypePrivate)
    {
        XMPPvCardTemp * card = [[DCXMPPTool shareInstance].xmppvCardTempModule vCardTempForJID:self.targetJID shouldFetch:YES];
        
        self.title = card.nickname;
    }
    
    [self setRightItem];
    
    
    
    
    tempImageCellArray = [[NSMutableArray alloc]initWithCapacity:1];
    for (int i=0; i<tempCount; i++) {
        DCImageChatTableViewCell * cell = [[DCImageChatTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellImage"];
        [tempImageCellArray addObject:cell];
    }
    
    tempTextCellArray = [[NSMutableArray alloc]initWithCapacity:1];
    for (int i=0; i<tempCount; i++) {
        DCTextChatTableViewCell * cell =[[DCTextChatTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellText"];
        [tempTextCellArray addObject:cell];
    }

    
    
    CGRect rect = self.view.bounds;
    rect.size.height-=toolBarHeight;
    
    self.tableView = [[UITableView alloc]initWithFrame:rect];
    self.tableView.delegate =self;
    self.tableView.dataSource =self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];

    [self.view addSubview:self.tableView];
    
    self.view.userInteractionEnabled = YES;
   
    self.tableView.canCancelContentTouches=YES;
    self.tableView.delaysContentTouches=NO;
    
    
    
    
    // Remove touch delay (since iOS 8)
    UIView *wrapView = self.tableView.subviews.firstObject;
    // UITableViewWrapperView
    if (wrapView && [NSStringFromClass(wrapView.class) hasSuffix:@"WrapperView"]) {
        for (UIGestureRecognizer *gesture in wrapView.gestureRecognizers) {
            // UIScrollViewDelayedTouchesBeganGestureRecognizer
            if ([NSStringFromClass(gesture.class) containsString:@"DelayedTouchesBegan"] ) {
                gesture.enabled = NO;
                break;
            }
        }
    }
    
//    self.tableView.decelerationRate= 0.85;
    
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tableViewTaped:)];
    self.tableView.userInteractionEnabled=YES;
    [self.tableView addGestureRecognizer:tap];
    
    
    self.tableView.showsHorizontalScrollIndicator=NO;
    self.tableView.showsVerticalScrollIndicator =NO;
    
    
    inputView= [DCChatInputView shareInstance];
    inputView.delegate =self;
    [inputView setFrame:CGRectMake(0, self.view.bounds.size.height-toolBarHeight, inputView.bounds.size.width, toolBarHeight)];
    
    [self.view addSubview:inputView];
    
    [self loadData];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loadData) name:kXMPP_MESSAGE_CHANGE object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(roomConfigChanged:) name:kDidFetchConfigurationForm object:nil];

}

#pragma mark - 右侧按钮
-(void)setRightItem
{
    
    UIImage * image ;
    
    
    
    if (self.conversationType==DCConversationTypePrivate) {
        image = [UIImage imageNamed:@"icon_me"];
    }
    else
    {
        image = [UIImage imageNamed:@"icon_group"];
    }
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(rightItemEvent)];
}

-(void)rightItemEvent
{
    [inputView hideAllInputViews];
    
    if (self.conversationType==DCConversationTypePrivate)
    {
        DCIMUserInfoViewController * vc = [[DCIMUserInfoViewController alloc]init];
        vc.userJid = self.targetJID;
        [self.navigationController pushViewController:vc animated:YES];
    }
    else
    {
        
        DCIMGroupChatSettingViewController * vc = [[DCIMGroupChatSettingViewController alloc]init];
        
        
        vc.room = self.room;
        [self.navigationController pushViewController:vc animated:YES];
        
        
    }
}
#pragma mark - data
-(void)loadData
{
    
    XMPPMessageArchivingCoreDataStorage *storage = [DCXMPPTool shareInstance].xmppMessageArchivingCoreDataStorage;
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:storage.messageEntityName inManagedObjectContext:storage.mainThreadManagedObjectContext];
    [fetchRequest setEntity:entity];
    
    // Specify criteria for filtering which objects to fetch
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"bareJidStr = %@", self.targetJID.bare];
    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timestamp"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [storage.mainThreadManagedObjectContext executeFetchRequest:fetchRequest error:&error];
    
    if (fetchedObjects!=nil) {
        dataSource = [NSMutableArray arrayWithArray:fetchedObjects];
    }
    
    
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.tableView reloadData];
            [self tableViewScrollToBottom];

        });
    });
    
}

#pragma mark - 滚动控制输入的显示和隐藏
-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    if (scrollView==self.tableView) {
        willBeginDeceleratePoint = scrollView.contentOffset;
    }
 
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (scrollView==self.tableView) {
        
        if (scrollView.contentOffset.y>willBeginDeceleratePoint.y) {
            if (![inputView isInputViewFirstResponder])
            {
//                [inputView.textInputView becomeFirstResponder];
            }
        }
        else
        {
            if ([inputView isInputViewFirstResponder])
            {
                [inputView hideAllInputViews];
            }
            
        }

    }
    
  
}


#pragma mark - private method

-(void)roomConfigChanged:(NSNotification*)noti
{
    XMPPRoom* room = noti.object;
    
    if ([room.roomJID.full isEqualToString:self.room.roomJID.full]) {
        self.title = [[DCIMGroupManager shareInstance]getRoomNameWithRoomJid:self.room.roomJID];
    }
}

-(void)tableViewTaped:(UIGestureRecognizer*)sender
{
    [inputView hideAllInputViews];
}

-(void)sendTextMessage
{
    
    
    XMPPMessage * message =  [DCMessageSender            messageWithMessageType:self.conversationType==DCConversationTypePrivate?privateMessage:groupMessage
                                 andSubType:textMessage
                                  forString:inputView.textInputView.text
                              addtionXMLs:nil
                                     toUser:self.targetJID
                           autoSendToServer:self.conversationType==DCConversationTypePrivate?YES:NO ];
    
    if (self.conversationType==DCConversationTypeGroup) {
        [self.room sendMessage:message];
    }
    
    inputView.textInputView.text = @"";
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        dispatch_async(dispatch_get_main_queue(), ^{
         
            [self.tableView reloadData];
            [self tableViewScrollToBottom];
        });
    });
    
    
}


-(void)tableViewScrollToBottom
{
    if (dataSource.count > 0) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:dataSource.count-1];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }
    
}

#pragma mark - chatInputView delegate
-(void)DCChatInputViewFrameChanged
{
    [self.tableView setContentInset:UIEdgeInsetsMake(self.tableView.contentInset.top, self.tableView.contentInset.left, inputView.superview.bounds.size.height-inputView.frame.origin.y-toolBarHeight, self.tableView.contentInset.right)];
    [self tableViewScrollToBottom];
    
}

-(void)DCChatInputViewSendTextMessage:(NSString *)text
{
    [self sendTextMessage];
}

-(void)DCChatVoiceInputRecored:(NSData *)voiceData isUserCanceled:(BOOL)isCanceled
{
    if (!isCanceled) {
        
    }
}

-(void)chatExtraView:(DCChatExtraView *)extraView selectedForIndex:(NSInteger)index
{
    
    if (index==0) {
        UIImagePickerController * _picker;
        _picker = [[UIImagePickerController alloc] init];
        _picker.delegate = self;
        _picker.allowsEditing = YES;
        _picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
      
        
        [self presentViewController:_picker animated:YES completion:nil];

    }
    
    
    if (index==2) {
        DCIMMapViewController * vc =[[DCIMMapViewController alloc]init];
        vc.targetJID = self.targetJID;
        vc.conversationType=self.conversationType;
        [self.navigationController pushViewController:vc animated:YES];
    }
}



#pragma mark - tableview delegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    XMPPMessageArchiving_Message_CoreDataObject * CoreDatamessage = dataSource[indexPath.section];
    
    XMPPMessage * message = CoreDatamessage.message;
    
    if ([[[[message elementsForName:subMessageType] firstObject] stringValue] isEqualToString:textMessage]) {
        
        return [tempTextCellArray[indexPath.section%tempCount] heightFor:CoreDatamessage];
        
    }
    else if ([[[[message elementsForName:subMessageType] firstObject] stringValue] isEqualToString:imageMessage])
    {
        
        
        return  [tempImageCellArray[indexPath.section%tempCount] heightFor:CoreDatamessage];
        
    }
    else
    {
          return [tempTextCellArray[indexPath.section%tempCount] heightFor:CoreDatamessage];
    }

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return dataSource.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XMPPMessageArchiving_Message_CoreDataObject * CoreDatamessage = dataSource[indexPath.section];
    
    XMPPMessage * message = CoreDatamessage.message;
    
    if ([[[[message elementsForName:subMessageType] firstObject] stringValue] isEqualToString:textMessage]) {
        
        return tempTextCellArray[indexPath.section%tempCount];
    }
    else if ([[[[message elementsForName:subMessageType] firstObject] stringValue] isEqualToString:imageMessage])
    {
        
        DCImageChatTableViewCell * cell =tempImageCellArray[indexPath.section%tempCount];
        
        return cell;
        
    }
    
    
    return tempTextCellArray[indexPath.section%tempCount];

}

#pragma mark - imagePicker
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage * choseImage = info[UIImagePickerControllerEditedImage];
    
    NSData * data = UIImageJPEGRepresentation(choseImage, 0.5);
    
    UIImage * image = [UIImage imageWithData:data];
    
    image = [DTImageScale imageWithMaxSide:640 sourceImage:image];
    
    if (image) {
        data = UIImageJPEGRepresentation([image fixOrientation], 0.3);
    }
    
  
    
    if (data) {
        
        
    
        
        [DCMessageSender messageWithMessageType:self.conversationType==DCConversationTypePrivate?privateMessage:groupMessage andSubType:imageMessage forString:@"http://192.168.199.183:8080/fileTest.jpeg" addtionXMLs:nil toUser:self.targetJID autoSendToServer:YES];
        
        
    }
    else
    {
        //获取资源失败
    }
    
    
    
}



@end
